<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <!--<el-form-item label="业务类别：">-->
          <!--<el-select-->
          <!--v-model="listQuery.deptType"-->
          <!--placeholder="全部"-->
          <!--clearable-->
          <!--class="input-width"-->
          <!--@change="deptTypeChange"-->
          <!--disabled>-->
          <!--<el-option-->
          <!--v-for="(item,index) in typeOptions"-->
          <!--:key="index"-->
          <!--:label="item.label"-->
          <!--:value="item.value">-->
          <!--</el-option>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <el-form-item label="机构名称：">
            <el-input v-model="listQuery.deptName" class="input-width" placeholder="机构名称"></el-input>
          </el-form-item>
          <el-form-item label="业务范围：">
            <el-cascader
              v-model="deptRangeList"
              :options="options"
              clearable
              @change="handleChange"></el-cascader>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()">新增机构</el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%;"
        v-loading="listLoading"
        border>
        <el-table-column label="机构名称" align="center">
          <template slot-scope="scope">{{ scope.row.deptName }}</template>
        </el-table-column>
        <el-table-column label="业务类别" align="center">
          <template slot-scope="scope">{{ scope.row.deptTypeName }}</template>
        </el-table-column>
        <el-table-column label="业务范围" align="center">
          <template slot-scope="scope">{{ scope.row.deptRange }}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">{{ status[scope.row.status].name }}</template>
        </el-table-column>
        <el-table-column label="录入时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.createTime | formatDateTime }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="umsDeptGet(scope.$index, scope.row)">
              查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="del(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑/新增数据':'机构详情'"
      :visible="dialogVisible"
      @close="closedialogVisible"
      width="40%">
      <el-form
        :model="admin"
        :rules="rules"
        ref="courseFrom"
        label-width="150px"
        size="small">
        <el-form-item label="机构名称：" prop="deptName">
          <el-input v-model="admin.deptName" v-show="isEdit" style="max-width: 250px" placeholder="机构名称"></el-input>
          <div style="max-width: 250px" v-show="!isEdit">{{ admin.deptName }}</div>
        </el-form-item>
        <el-form-item label="业务类别：" prop="deptType">
          <div style="max-width: 250px">社区教育</div>
          <!--<el-select-->
          <!--v-model="admin.deptType"-->
          <!--style="max-width: 250px"-->
          <!--:disabled="!isEdit"-->
          <!--:placeholder="admin.deptTypeName"-->
          <!--v-show="isEdit"-->
          <!--clearable-->
          <!--disabled-->
          <!--&gt;-->
          <!--<el-option-->
          <!--v-for="(item,index) in typeOptions"-->
          <!--:key="index"-->
          <!--:label="item.label"-->
          <!--:value="item.value">-->
          <!--</el-option>-->
          <!--</el-select>-->
        </el-form-item>
        <el-form-item label="业务范围：">
          <div style="max-width: 250px" v-show="!isEdit">{{ admin.deptRange }}</div>
          <el-tree
            v-if="isEdit"
            style="margin-top: 0;max-width: 250px"
            :data="options"
            node-key="id"
            show-checkbox
            ref="tree"
            @check-change="handleCheckChange">
          </el-tree>
        </el-form-item>
        <el-form-item label="城市：">
          <el-input v-model="admin.cityName" v-show="isEdit" style="max-width: 250px" placeholder="城市"></el-input>
          <div style="max-width: 250px" v-show="!isEdit">{{ admin.cityName }}</div>
        </el-form-item>
        <el-form-item label="简介：">
          <el-input v-model="admin.deptDesc" v-show="isEdit" style="max-width: 250px" placeholder="简介"></el-input>
          <div style="max-width: 250px" v-show="!isEdit">{{ admin.deptDesc }}</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedialogVisible" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small" v-show="isEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { umsDeptList, umsDeptDel, commonListLB, updateUmsDept, saveUmsDept } from '@/api/login'
import { curCourseTypeList } from '@/api/course'
import { formatDate } from '@/utils/date'

const defaultListQuery = {
  deptType: 2,
  pageNum: 1,
  pageSize: 10
}
const umsData = {
  'deptDesc': '',
  'deptName': '',
  'deptRange': '',
  'deptRangeList': [],
  'deptType': 2,
  'deptTypeName': '社区教育'
}
export default {
  name: 'AdminList',
  data () {
    return {
      courseTypeOptions: '',
      addUms: false,
      deptType: '',
      deptRangeList: [],
      typeOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      value: [],
      options: [],
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, umsData),
      isEdit: false,
      status: [
        { name: '非合作' },
        { name: '合作中' }
      ],
      count: 1,
      rules: {
        deptName: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        // deptType: [
        //   { required: true, message: '请选择', trigger: 'blur' }
        // ],
        deptRangeList: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getList()
    commonListLB().then(response => {
      const list = response.data
      list.map((item) => {
        const { id, commonCode, commonDesc } = item
        const listB = {
          id: id,
          value: parseInt(commonCode),
          label: commonDesc
        }
        this.typeOptions.push(listB)
      })
    })
    curCourseTypeList({ deptType: 2, pageSize: 100 }).then(response => {
      const list = response.data.list
      this.courseTypeOptions = response.data.list
      let a = 0
      let listB = {}
      list.map((item) => {
        const { id, typeName, subset } = item
        const children = []
        if (subset) {
          subset.map((i) => {
            const { id, typeName } = i
            const listA = {
              id: id,
              value: id,
              label: typeName,
              parentId: a
            }
            children.push(listA)
          })
        }
        if (subset) {
          listB = {
            id: id,
            value: id,
            label: typeName,
            children: children
          }
        } else {
          listB = {
            id: id,
            value: id,
            label: typeName
          }
        }

        this.options.push(listB)
        a = a + 1
      })
    })
  },
  filters: {
    formatDateTime (time) {
      if (time == null || time === '') {
        return 'N/A'
      }
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  methods: {
    handleAdd () {
      this.admin = umsData
      setTimeout(() => {
        // this.$refs['courseFrom'].resetFields()
        this.$refs.tree.setCheckedKeys(this.admin.deptRangeList)
      }, 0)
      this.dialogVisible = true
      this.isEdit = true
      this.addUms = true
    },
    closedialogVisible () {
      this.dialogVisible = false
      this.addUms = false
      this.admin = umsData
    },
    handleDialogConfirm () {
      this.$refs['courseFrom'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          if (!this.addUms) {
            updateUmsDept(this.admin.id, this.admin).then(response => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.$refs.tree.setCheckedKeys([])
              this.getList()
            })
          } else {
            saveUmsDept(this.admin.id, this.admin).then(response => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.$refs.tree.setCheckedKeys([])
              this.getList()
            })
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleCheckChange (data, checked, indeterminate) {
      const list = this.$refs.tree.getCheckedKeys()
      const dataNode = this.$refs.tree.getCheckedNodes()
      dataNode.map((item) => {
        if (!isNaN(item.parentId)) {
          list.push(this.options[item.parentId].id)
        }
      })
      const res = new Map()
      const b = list.filter((a) => !res.has(a) && res.set(a, 1))
      this.admin.deptRangeList = b
    },
    handleChange (value) {
    },
    handleResetSearch () {
      this.listQuery = Object.assign({}, defaultListQuery)
      this.deptRangeList = []
    },
    handleSearchList () {
      this.listQuery.pageNum = 1
      if (this.deptRangeList && this.deptRangeList.length > 0) {
        this.listQuery.deptRange = this.deptRangeList[this.deptRangeList.length - 1]
      }
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    umsDeptGet (index, row) {
      this.dialogVisible = true
      this.isEdit = false
      this.addUms = false
      this.admin = Object.assign({}, row)
    },
    handleUpdate (index, row) {
      // this.admin = Object.assign({}, row)
      this.admin = Object.assign({}, row)
      console.log()
      this.dialogVisible = true
      this.isEdit = true
      this.addUms = false
      setTimeout(() => {
        // this.$refs['courseFrom'].resetFields()
        this.$refs.tree.setCheckedKeys(this.admin.deptRangeList)
      }, 0)
    },
    del (index, row) {
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        umsDeptDel({ id: row.id }).then(response => {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.dialogVisible = false
          this.getList()
        })
      })
    },
    getList () {
      this.listLoading = true
      umsDeptList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.list.map((item) => {
          item.cityName = '北京'
          return item
        })
        this.total = response.data.total
      })
    },
    deptTypeChange (e) {
      if (e === 1) {
        this.$router.push('/dept-ms/dept-life')
      }
    }
  }
}
</script>
<style></style>
